from django.shortcuts import render, get_object_or_404, redirect
from .models import Author

from django.views.generic import ListView, TemplateView


# 列出所有作者
def author_list(request):
    authors = Author.objects.all()
    return render(request, 'myapp/author_list.html', {'authors': authors})

# 创建新作者
def author_create(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        bio = request.POST.get('bio')
        birth_date = request.POST.get('birth_date') if request.POST.get('birth_date') else None
        
        author = Author.objects.create(
            name=name,
            bio=bio,
            birth_date=birth_date
        )
        return redirect('author_list')
    return render(request, 'myapp/author_create.html')

# 查看作者详情
def author_detail(request, pk):
    author = get_object_or_404(Author, pk=pk)
    return render(request, 'myapp/author_detail.html', {'author': author})

# 更新作者信息
def author_update(request, pk):
    author = get_object_or_404(Author, pk=pk)
    if request.method == 'POST':
        author.name = request.POST.get('name')
        author.bio = request.POST.get('bio')
        author.birth_date = request.POST.get('birth_date') if request.POST.get('birth_date') else None
        author.save()
        return redirect('author_detail', pk=author.pk)
    return render(request, 'myapp/author_update.html', {'author': author})

# 删除作者
def author_delete(request, pk):
    author = get_object_or_404(Author, pk=pk)
    if request.method == 'POST':
        author.delete()
        return redirect('author_list')
    return render(request, 'myapp/author_delete.html', {'author': author})